//
//  MHFMDB+Querry.m
//  数据库的读写封装
//
//  Created by zsgjs on 2017/2/21.
//  Copyright © 2017年 zsgjs. All rights reserved.
//

#import "MHFMDB+Querry.h"

@implementation MHFMDB (Querry)

/**
 *  传入字符串 获取指定字段名的值
 */
- (id)queryField:(NSString *)field
{
    NSDictionary *dict = [[self fieldsWithString:field] querySigleInfo];
    return [[dict allValues] lastObject];
}

/**
 *  查询单条记录
 */
- (NSDictionary *)querySigleInfo
{
    [self setLimit:@"1"];
    NSArray *arr = [self queryAll];
    NSDictionary *result = [NSDictionary dictionaryWithDictionary:[arr lastObject]];
    return result;
}
/**
 *  查询全部结果集合
 */
- (NSArray *)queryAll
{
    NSString *sql = [NSString stringWithFormat:@"SELECT %@ FROM `%@` %@ %@ %@;",self.fieldsString,self.currentTableName, self.where,self.order,self.limit];
    return [self excuteQueryWithSql:sql];
}

/**
 *  展示Table数据
 */
- (NSArray *)queryTableWithFields:(NSString *)fields
                             page:(NSUInteger)page
                         pageSize:(NSUInteger)pagesize
                        tableName:(NSString *)tableName
{
    return [self queryTableWithFields:fields
                                pages:page
                             pageSize:pagesize
                                order:nil
                            tableName:tableName];
}
/**
 *  展示Table数据
 */
- (NSArray *)queryTableWithPage:(NSUInteger)page
                       pageSize:(NSUInteger)pagesize
                      tableName:(NSString *)tableName
{
    return [self queryTableWithFields:nil
                                pages:page
                             pageSize:pagesize
                                order:nil
                            tableName:tableName];
}


/**
 *  展示Table数据
 */
- (NSArray *)queryTableWithPage:(NSUInteger)page
                       pageSize:(NSUInteger)pagesize
                          order:(NSString *)order
                      tableName:(NSString *)tableName
{
    return [self queryTableWithFields:nil
                                pages:page
                             pageSize:pagesize
                                order:order
                            tableName:tableName];
}

/**
 *  展示Table数据
 */
- (NSArray *)queryTableWithFields:(NSString *)fields
                            pages:(NSUInteger)page
                         pageSize:(NSUInteger)pagesize
                            order:(NSString *)order
                        tableName:(NSString *)tableName
{
    //重置查询条件
    [self clean];
    //选择要操作的表名
    [self setCurrentTableName:tableName];
    int startNum = page<=0 ? 0:(int)((page -1)*pagesize);
    int endNum = (int)(page*pagesize);
    //limit条件
    [self limitWithStart:startNum End:endNum];
    //field条件
    if (![fields isEqual:nil]) {
        [self fieldsWithString:fields];
    }
    //order条件
    if (![order isEqual:nil]) {
        [self setOrder:order];
    }
    //select查询
    NSArray *result = [self queryAll];
    return result;
    
}


@end
